package edu.sjtu.seda.experiment;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;


public class EventDriven implements Runnable{
	
	private BlockingQueue<EventDrivenRunner> queue;
	
	public EventDriven(){
		this.queue = new LinkedBlockingQueue<EventDrivenRunner>();
	}
	
	public void pushEvent(EventDrivenRunner event){
		this.queue.offer(event);
		synchronized (this) {
			notifyAll();
		}
	}
	
	public EventDrivenRunner popEvent(){
		try {
			return queue.take();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public int size(){
		return this.queue.size();
	}

	@Override
	public void run() {
		while(true){
			while(size()!=0){
				popEvent().run();
			}
			synchronized(this){
				try {
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	

}
